package com.jeesite.modules.platform.util;

import com.jeesite.common.config.Global;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.backlog.service.DcSupBacklogService;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.task.action.entity.DcSupTaskAction;
import com.jeesite.modules.task.action.service.DcSupTaskActionService;
import com.jeesite.modules.task.deploy.entity.DcSupTaskInfo;
import com.jeesite.modules.task.deploy.entity.DcSupTaskInfoMsgNum;
import com.jeesite.modules.task.deploy.service.DcSupTaskInfoService;
import com.jeesite.modules.task.receive.entity.TaskReceiveDto;
import com.jeesite.modules.task.receive.service.TaskReceiveService;
import com.jeesite.modules.task.status.service.DcSupTaskStatusService;
import com.jeesite.modules.yzw.entity.MsgDetail;
import com.jeesite.modules.yzw.service.LehandYzwPushTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;

import java.util.*;

/**
 * User: ldj
 * Date: 2022/3/25
 * Time: 1:30
 * Description: restTemplate
 */
@Slf4j
@Service
public class HttpRestTemplateApi {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DcSupTaskInfoService dcSupTaskInfoService;
    @Autowired
    private DcSupTaskActionService dcSupTaskActionService;
    @Autowired
    private TaskReceiveService taskReceiveService;
    @Autowired
    private DcSupTaskStatusService dcSupTaskStatusService;
    @Autowired
    private LehandYzwPushTask lehandYzwPushTask;
    @Autowired
    private DcSupBacklogService dcSupBacklogService;
    @Transactional(readOnly=false)
    public  void dcDataTransferDownData() throws Exception {
        String platform_url = Global.getConfig("platform.dcDataTransfer.downData");
        String token = Global.getConfig("platform.dcDataTransfer.token");
        String orgCode = Global.getConfig("platform.dcDataTransfer.orgCode");
        String sendId = Global.getConfig("platform.dcDataTransfer.sendId");//"11012"
        String receviceId = Global.getConfig("platform.dcDataTransfer.receviceId");//"5166"
        String url = platform_url+"?orgCode=%s&limit=%s&bizKey=%s";
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        headers.add("token",token);
        //提交参数设置
         url = String.format(url, orgCode, "50", "baseData");
        HttpEntity formEntity = new HttpEntity<>(headers);
        //使用JSONObject，不需要创建实体类VO来接受返参，缺点是别人不知道里面有哪些字段,即不知道有那些key
        JSONObject body1 = restTemplate.postForObject(url, formEntity, JSONObject.class);
        String bizIds ="";
        List<Map> array =  (List) body1.get("data");
        int i =0;
        for(Map info : array){
            String blongArea  = (String)info.get("blongArea");

            String bizId  = (String)info.get("bizId");
            if(StringUtils.isNotBlank(bizIds)){
                bizIds = bizIds+","+bizId;
            }else {
                bizIds =bizIds+bizId;
            }

//            if(!blongArea.contains("芜湖市")){
//                continue;
//            }
            i++;
            String problemCategory  = (String)info.get("problemCategory");
            String msgTitle  = (String)info.get("msgTitle");
            String msgContent  = (String)info.get("msgContent");
            String personName  = (String)info.get("personName");
            String mobilePhone  = (String)info.get("mobilePhone");
            String nibanOpinion  = (String)info.get("nibanOpinion");
            String reportEndDate  = (String)info.get("reportEndDate");
            reportEndDate = reportEndDate+" 23:59";
            String messageTime  = (String)info.get("messageTime");
            DcSupTaskInfo dcSupTaskInfo = new DcSupTaskInfo();
            dcSupTaskInfo.setTaskTitle(msgTitle);
            dcSupTaskInfo.setTaskYear(DateUtils.getYear());
            dcSupTaskInfo.setTaskContent(msgContent);
            dcSupTaskInfo.setTaskStartTime(DateUtils.parseDate(messageTime));
            dcSupTaskInfo.setTaskEndTime(DateUtils.parseDate(reportEndDate));
            dcSupTaskInfo.setTaskRequireName(nibanOpinion);
            dcSupTaskInfo.setContactPhone(mobilePhone);
            dcSupTaskInfo.setContactName(personName);
            dcSupTaskInfo.setFeedbackWay("4");
            dcSupTaskInfo.setTaskLeaderOrg("241");
            dcSupTaskInfo.setTaskLeaderOrgName("市委督查办公室（市政府督查办公室）");
            dcSupTaskInfo.setTaskTypeCode("999");
            dcSupTaskInfo.setTaskTypeName("省督查平台同步任务");
            dcSupTaskInfo.setCreateBy(sendId);
            dcSupTaskInfo.setCreateDate(new Date());
            DcSupTaskInfoMsgNum dcSupTaskInfoMsgNum = new DcSupTaskInfoMsgNum();
            dcSupTaskInfoMsgNum.setMsgNum("省政督〔"+DateUtils.getYear()+"〕");
            Integer  num = 0;
            DcSupTaskInfoMsgNum res = dcSupTaskInfoService.getMaxMessageNumberByType(dcSupTaskInfoMsgNum);

            if(res==null){
                res = new DcSupTaskInfoMsgNum();
                res.setMsgNum2("0");

            }
            num = Integer.parseInt(res.getMsgNum2())+1;
            dcSupTaskInfo.setMessageNumber("省政督〔"+DateUtils.getYear()+"〕"+num);

            dcSupTaskInfo.setPlatformJson(JSONObject.toJSONString(info));
            // 获取当前会话对象
            dcSupTaskInfo.setCreateOrg("241");
            dcSupTaskInfo.setCreateOrgName("市委督查办公室（市政府督查办公室）");
            dcSupTaskInfo.setCreateUnit("241");
            dcSupTaskInfo.setCreateUnitName("市委督查办公室（市政府督查办公室）");
            dcSupTaskInfo.setDecomposeFlag("0");
            dcSupTaskInfo.setParentTaskId("0");
            dcSupTaskInfo.setSourceTaskId("0");
            dcSupTaskInfo.setNormalFlag("1");
            dcSupTaskInfo.setTaskStatus("2");
            dcSupTaskInfoService.save(dcSupTaskInfo);
            DcSupTaskAction dcSupTaskAction  = new DcSupTaskAction();
            dcSupTaskAction.setTaskId(dcSupTaskInfo.getId());
            List<DcSupTaskAction> list = dcSupTaskActionService.findList(dcSupTaskAction);
            if(list != null && list.size() > 0){
                //给牵头单位自动接收
                DcSupTaskAction action = list.get(0);
                action.setTransferFlag("1");
                action.setTransferOrgCode(receviceId);
                action.setTransferOrgName("戴继松");
                action.setTaskReceiveTime(new Date());
                action.setTaskStatus("2");
                action.setUpdateBy(receviceId);
                dcSupTaskActionService.update(action);

                //写入statue表
                dcSupTaskStatusService.addStatus(action.getId(),"2","2","已接收");
                //清掉之前的转办待办
                dcSupBacklogService.doBacklog(action.getId(),"task_transfer");
                //新增待办
                dcSupBacklogService.add("督查督办","任务待办","转办待反馈","提示信息"
                        ,"您有一个任务:" + dcSupTaskInfo.getTaskTitle() + "待反馈,请及时查看"
                        ,"/a/action/dcSupTaskAction/noCompleteView",""
                        ,action.getId(),"task_transfer",action.getTransferOrgCode()
                        ,dcSupTaskInfo.getId(),action.getId());
                //定时任务的代办置为已办
                dcSupBacklogService.doBacklog(action.getId(),"task_yuqi");

            }
        }
        if(i>0) {
            MsgDetail msgDetail = new MsgDetail();
            msgDetail.setSendid(sendId);
            msgDetail.setSubjectid(receviceId);
            msgDetail.setMesg("您有" + i + "个省政府督办任务需要反馈,请及时登录系统查看");
            lehandYzwPushTask.pushYzwShortMsg(msgDetail);
        }
        System.out.println(bizIds);

        ObjectMapper objectMapper = new ObjectMapper();
        log.info("body1:{}",objectMapper.writeValueAsString(body1));
        if(StringUtils.isNotBlank(bizIds)) {
            String confirmData_url = Global.getConfig("platform.dcDataTransfer.confirmData");
            String url2 = confirmData_url + "?orgCode=%s&bizIds=%s&bizKey=%s";
            //提交参数设置
            url = String.format(url2, orgCode, bizIds, "baseData");
            //使用JSONObject，不需要创建实体类VO来接受返参，缺点是别人不知道里面有哪些字段,即不知道有那些key
            JSONObject body2 = restTemplate.postForObject(url, formEntity, JSONObject.class);
            Integer code = (Integer) body2.get("code");
            if (code != 0) {
                throw new Exception("失败");
            }
            log.info("body2:{}", objectMapper.writeValueAsString(body2));
        }
    }

}
